"use strict"

/**
 * 全文检索/索引 支持
 *  
 */

var q = require("q");
var solr = require('solr-client');
// Create a client 
var solrConfig = {
    "host": "127.0.0.1",
    "port": 8983,
    "path": "/solr",
    "core": "zb_core"
};
var client = solr.createClient(solrConfig);
client.autoCommit = true;

var db = require("../db");

const TICKET_CNT = 1000;

var outObject = {

};

var loopFn = function (startIndex) {
    return function () {
        var def = q.defer();
        var result = q("");
        var sql = "select * from items order by id desc limit " + TICKET_CNT + " offset " + startIndex * TICKET_CNT;
        console.log("sql-> " + sql);
        db.query(sql, function (err, recs) {
            if (recs) {
                var docs = [];
                for (var i = 0, j = recs.length; i < j; i++) {
                    var item = recs[i];
                    var doc = { id: item.id, title: item.title, url: item.url, source: item.source, create_time: item.create_time };
                    docs.push(doc);
                }
                outObject.add(docs, function (err, obj) {
                    if (err) {
                        console.error(err);
                    } else {
                        if (obj.responseHeader.status == 0) {
                            console.log("索引创建成功！");
                        } else {
                            console.log("索引创建失败！");
                        }
                    }
                    def.resolve();
                });
            } else {
                console.log("没有发现记录");
                def.resolve();
            }
        });
        return def.promise;
    };
};


outObject.indexAll = function (fn) {
    var result = q("");
    var cnt = 0;
    result.then(function () {
        var def = q.defer();
        db.query("select count(*) as total from items", function (err, recs) {
            if (recs) {
                cnt = recs[0]["total"];
            }
            def.resolve();
        });
        return def.promise;
    }).then(function () {
        var def = q.defer();
        var inner = q();
        var ticket = parseInt((cnt + TICKET_CNT - 1) / TICKET_CNT);
        console.log("items: " + cnt + " ticket: " + ticket);
        for (var i = 0; i < ticket; i++) {
            inner = inner.then(loopFn(i));
        }
        inner.then(function () {
            def.resolve();
        });
        return def.promise;
    }).then(function () {
        console.log("all items indexed");
        if (fn) fn();
    });;
};

outObject.add = function (items, cb) {
    client.add(items, { commit: true }, function (err, obj) {
        if (err) {
            console.error(err);
        } else {
            if (obj.responseHeader.status != 0) {
                console.log("索引创建失败！");
            }
        }
        if (cb) cb(err, obj);
    });
};

outObject.getBeforeDate = function (before) {
    var startDay = Date.today();
    startDay = startDay.remove({ "days": before });
    return startDay;
};

outObject.query = function (query, start, rows, cb) {
    var create_time = query.create_time;
    if (create_time) {
        delete query.create_time;
    }
    // console.log(JSON.stringify(query));
    var queryTerm = client.createQuery()
        .q(query).start(start).rows(rows).sort({ "id": "desc" });
    if (create_time) {
        // console.log("create_time: " + JSON.stringify(create_time));
        queryTerm.rangeFilter(create_time);
    }
    client.search(queryTerm, function (err, data) {
        cb(err, data);
    });
};

exports = module.exports = outObject;